# -*- encoding: utf-8 -*-
'''

Utility functions, including logger & voltage check.

@File    :   utils.py
@Time    :   2021/12/05 19:10:25
@Author  :   Yangshuo He
@Contact :   sugarhe58@gmail.com
'''

import logging
from vcgencmd import Vcgencmd
from logging import handlers

def myLog(log_path):
    """
    Provider logger that write log file & print log message to terminal.
    Input:
        log_path - path to the log file
    """
    logger = logging.getLogger("supervise")
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger.setLevel(logging.DEBUG)
    # write into file
    th = handlers.TimedRotatingFileHandler(filename=log_path,when="D",backupCount=5,encoding='utf-8')
    # write into terminal
    sh = logging.StreamHandler()
    # set log message format
    th.setFormatter(formatter)
    sh.setFormatter(formatter)
    # add object to logger
    logger.addHandler(th)
    logger.addHandler(sh)

    return logger


# Flag Bits
flags = {
    "UNDERVOLTED"         : '0',
    "CAPPED"              : '1',
    "THROTTLED"           : '2',
    "SOFT_TEMPLIMIT"      : '3',
    "HAS_UNDERVOLTED"     : '16',
    "HAS_CAPPED"          : '17',
    "HAS_THROTTLED"       : '18',
    "HAS_SOFT_TEMPLIMIT"  : '19',
}

def checkPi():
    """
    Check the voltage
    """
    throttled = Vcgencmd().get_throttled()
    log_message = ""
    for key,value in flags.items():
        if throttled['breakdown'][value]:
            log_message += "{} ".format(key)
    
    if log_message == "":
        log_message = None

    return log_message